package com.ajnp.springcloud.controller;


import com.ajnp.springcloud.service.PaymentService;
import entities.CommonResult;
import entities.Payment;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Time;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/payment")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    //获取当前服务的端口号
    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @PostMapping("/getcreate")
    //使用@RequestBody 进行数据绑定
    //因为post请求默认的发送格式时json格式对象 所有后端接收必须使用@RequestBody注解进行接收
    public CommonResult create(@RequestBody Payment payment) {
        int cont = paymentService.create(payment);
        log.info("插入结果为：" + cont);

        if (cont >= 1) {
            return new CommonResult(200, "插入数据成功，serverPost：" + serverPort, cont);
        } else {
            return new CommonResult(500, "插入数据异常");
        }
    }

    @GetMapping("/getpaymentById/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        Payment paymentById = paymentService.getPaymentById(id);
        log.info("插入结果为：" + paymentById);
        int a = 3 / 2;
        int s = 2 / 3;
        if (paymentById != null) {
            return new CommonResult(200, "查询成功,serverPost:" + serverPort, paymentById);
        } else {
            return new CommonResult(500, "查询失败:没有查询的数据" + id);
        }
    }

    @GetMapping("/discovery")
    public Object discovery() {
        //获取所有的服务名称
        List<String> services = discoveryClient.getServices();
        for (String service : services) {
            log.info("####services:" + service);
        }
        //  获取服务的实例
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        for (ServiceInstance instance : instances) {
            log.info("服务名" + instance.getServiceId() + "\t" + "主机名称：" + instance.getHost() + "\t服务端口号" + instance.getPort() + "\t 获取服务的uri地址：" + instance.getUri());
        }

        return this.discoveryClient;
    }

    @GetMapping("/lb")
    public String getPaymentLB() {
        //返回 当前的端口号
        return serverPort;
    }


    @GetMapping("/paymentsleep")
    public String paymentFeignTimeout() {

        try {
            //当前线程暂停3秒
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

    @GetMapping("/getzipkin")
    public String getzipkin() {
        return "当前为：" + serverPort + ":端口 调用方法getzipkin()  ヽ(゜▽゜　)－C<(/;◇;)/~";
    }


}
